<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client Certificates - CertMate</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @media (prefers-color-scheme: dark) {
            html {
                background-color: #111827 !important;
            }
        }
    </style>
    <script>
        tailwind.config = {
            darkMode: 'media',
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#1e40af',
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 dark:bg-gray-900 min-h-screen transition-colors duration-200">
    <!-- Navigation -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm border-b dark:border-gray-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-shield-alt text-primary text-2xl"></i>
                    </div>
                    <div class="ml-3">
                        <h1 class="text-xl font-semibold text-gray-900 dark:text-white">CertMate</h1>
                        <p class="text-sm text-gray-500 dark:text-gray-400">SSL Certificate Manager</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="/" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-certificate mr-1"></i> Server Certs
                    </a>
                    <a href="/client-certificates" class="px-3 py-2 rounded-md text-sm font-medium text-primary bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700">
                        <i class="fas fa-id-card mr-1"></i> Client Certs
                    </a>
                    <a href="/settings" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-cog mr-1"></i> Settings
                    </a>
                    <a href="/help" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-question-circle mr-1"></i> Help
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Statistics Bar -->
        <div class="grid grid-cols-1 gap-4 md:grid-cols-4 mb-6">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border-l-4 border-blue-500">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-gray-500 dark:text-gray-400 text-sm">Total Certificates</p>
                        <p class="text-3xl font-bold text-gray-900 dark:text-white" id="totalCount">0</p>
                    </div>
                    <i class="fas fa-certificate text-blue-500 text-3xl opacity-20"></i>
                </div>
            </div>
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border-l-4 border-green-500">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-gray-500 dark:text-gray-400 text-sm">Active</p>
                        <p class="text-3xl font-bold text-gray-900 dark:text-white" id="activeCount">0</p>
                    </div>
                    <i class="fas fa-check-circle text-green-500 text-3xl opacity-20"></i>
                </div>
            </div>
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border-l-4 border-red-500">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-gray-500 dark:text-gray-400 text-sm">Revoked</p>
                        <p class="text-3xl font-bold text-gray-900 dark:text-white" id="revokedCount">0</p>
                    </div>
                    <i class="fas fa-ban text-red-500 text-3xl opacity-20"></i>
                </div>
            </div>
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border-l-4 border-purple-500">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-gray-500 dark:text-gray-400 text-sm">By Usage</p>
                        <p class="text-sm text-gray-600 dark:text-gray-300 mt-2" id="usageBreakdown">Loading...</p>
                    </div>
                    <i class="fas fa-chart-pie text-purple-500 text-3xl opacity-20"></i>
                </div>
            </div>
        </div>

        <!-- Create Certificate Form -->
        <div class="bg-white dark:bg-gray-800 shadow-lg rounded-xl mb-6 border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div class="px-6 py-5 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
                            <i class="fas fa-plus-circle mr-2 text-primary"></i>
                            Create Client Certificate
                        </h3>
                        <p class="text-sm text-gray-600 dark:text-gray-300 mt-1">For mTLS, VPN, or user authentication</p>
                    </div>
                </div>
            </div>
            <div class="px-6 py-6">
                <!-- Tab Selection -->
                <div class="flex space-x-4 mb-6 border-b border-gray-200 dark:border-gray-700">
                    <button id="singleTabBtn" class="px-4 py-2 border-b-2 border-primary text-primary font-medium">
                        <i class="fas fa-user mr-1"></i> Single Certificate
                    </button>
                    <button id="batchTabBtn" class="px-4 py-2 border-b-2 border-transparent text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white font-medium">
                        <i class="fas fa-users mr-1"></i> Bulk Upload (CSV)
                    </button>
                </div>

                <!-- Single Certificate Form -->
                <form id="createCertForm" class="space-y-6">
                    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
                        <div>
                            <label for="commonName" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-user mr-2 text-blue-500"></i>Common Name (Required)
                            </label>
                            <input type="text" id="commonName" name="commonName" placeholder="e.g., john.doe@example.com"
                                   class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary"
                                   required>
                        </div>
                        <div>
                            <label for="email" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-envelope mr-2 text-blue-500"></i>Email
                            </label>
                            <input type="email" id="email" name="email" placeholder="user@example.com"
                                   class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
                        <div>
                            <label for="organization" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-building mr-2 text-blue-500"></i>Organization
                            </label>
                            <input type="text" id="organization" name="organization" value="CertMate" placeholder="Your Organization"
                                   class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="certUsage" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-tag mr-2 text-blue-500"></i>Usage Type
                            </label>
                            <select id="certUsage" name="certUsage"
                                    class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                                <option value="api-mtls">API mTLS</option>
                                <option value="vpn">VPN Access</option>
                                <option value="user-auth">User Authentication</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
                        <div>
                            <label for="daysValid" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-calendar mr-2 text-blue-500"></i>Valid For (Days)
                            </label>
                            <input type="number" id="daysValid" name="daysValid" value="365" min="1" max="3650"
                                   class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="notes" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-sticky-note mr-2 text-blue-500"></i>Notes
                            </label>
                            <input type="text" id="notes" name="notes" placeholder="Optional notes..."
                                   class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                        </div>
                    </div>

                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="generateKey" name="generateKey" checked
                               class="w-4 h-4 text-primary bg-gray-100 border-gray-300 rounded focus:ring-2 focus:ring-primary">
                        <label for="generateKey" class="text-sm text-gray-700 dark:text-gray-300">
                            <i class="fas fa-lock mr-1"></i>Generate private key (recommended)
                        </label>
                    </div>

                    <button type="submit" class="w-full bg-primary hover:bg-secondary text-white font-semibold py-3 rounded-lg transition duration-200 flex items-center justify-center">
                        <i class="fas fa-check-circle mr-2"></i> Create Certificate
                    </button>
                </form>

                <!-- Batch Upload Form (Hidden by default) -->
                <div id="batchForm" class="hidden space-y-6">
                    <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                        <p class="text-sm text-blue-800 dark:text-blue-300">
                            <i class="fas fa-info-circle mr-2"></i>
                            Upload a CSV file with columns: common_name, email, organization, cert_usage (optional), notes (optional)
                        </p>
                    </div>

                    <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center cursor-pointer hover:border-primary transition"
                         id="dropZone">
                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 dark:text-gray-500 mb-3"></i>
                        <p class="text-gray-700 dark:text-gray-300 font-semibold mb-1">Drag and drop CSV file here</p>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">or click to select</p>
                        <input type="file" id="csvFile" name="csvFile" accept=".csv" class="hidden">
                    </div>

                    <div id="csvPreview" class="hidden bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                        <p class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">Preview (<span id="rowCount">0</span> rows)</p>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm" id="previewTable">
                                <thead class="bg-gray-200 dark:bg-gray-700">
                                    <tr id="headerRow"></tr>
                                </thead>
                                <tbody id="previewBody"></tbody>
                            </table>
                        </div>
                    </div>

                    <button type="button" id="submitBatchBtn" class="w-full bg-primary hover:bg-secondary text-white font-semibold py-3 rounded-lg transition duration-200 flex items-center justify-center hidden">
                        <i class="fas fa-upload mr-2"></i> Upload <span id="certCountText"></span> Certificates
                    </button>
                </div>
            </div>
        </div>

        <!-- Certificates List -->
        <div class="bg-white dark:bg-gray-800 shadow-lg rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div class="px-6 py-5 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700">
                <div class="flex items-center justify-between">
                    <h3 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
                        <i class="fas fa-list mr-2 text-primary"></i>
                        Client Certificates
                    </h3>
                    <div class="flex items-center space-x-2">
                        <input type="text" id="searchInput" placeholder="Search by CN or email..."
                               class="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                        <select id="filterUsage"
                                class="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                            <option value="">All Usage Types</option>
                            <option value="api-mtls">API mTLS</option>
                            <option value="vpn">VPN</option>
                            <option value="user-auth">User Auth</option>
                        </select>
                        <select id="filterStatus"
                                class="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-primary">
                            <option value="">All Status</option>
                            <option value="active">Active</option>
                            <option value="revoked">Revoked</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-100 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Common Name</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Email</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Usage</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Created</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Expires</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="certTableBody" class="divide-y divide-gray-200 dark:divide-gray-700">
                        <tr><td colspan="7" class="px-6 py-8 text-center text-gray-500 dark:text-gray-400">Loading certificates...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal for certificate details -->
    <div id="certModal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-bold text-gray-900 dark:text-white">Certificate Details</h3>
                <button onclick="closeCertModal()" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="modalContent" class="space-y-3 text-sm"></div>
            <div class="mt-6 flex space-x-3">
                <button onclick="downloadCertFile('crt')" class="flex-1 bg-blue-500 hover:bg-blue-600 text-white py-2 rounded px-3 text-sm font-semibold flex items-center justify-center">
                    <i class="fas fa-download mr-1"></i> .crt
                </button>
                <button onclick="downloadCertFile('key')" class="flex-1 bg-red-500 hover:bg-red-600 text-white py-2 rounded px-3 text-sm font-semibold flex items-center justify-center">
                    <i class="fas fa-download mr-1"></i> .key
                </button>
                <button onclick="downloadCertFile('csr')" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white py-2 rounded px-3 text-sm font-semibold flex items-center justify-center">
                    <i class="fas fa-download mr-1"></i> .csr
                </button>
            </div>
        </div>
    </div>

    <script>
        // Global state
        let currentCertId = null;
        let certificatesData = [];

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            loadStatistics();
            loadCertificates();
            setupEventListeners();
        });

        // Setup event listeners
        function setupEventListeners() {
            // Tab switching
            document.getElementById('singleTabBtn').addEventListener('click', () => switchTab('single'));
            document.getElementById('batchTabBtn').addEventListener('click', () => switchTab('batch'));

            // Single cert form
            document.getElementById('createCertForm').addEventListener('submit', handleCreateCert);

            // CSV upload
            const dropZone = document.getElementById('dropZone');
            dropZone.addEventListener('click', () => document.getElementById('csvFile').click());
            dropZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropZone.classList.add('border-primary', 'bg-blue-50', 'dark:bg-blue-900/20');
            });
            dropZone.addEventListener('dragleave', () => {
                dropZone.classList.remove('border-primary', 'bg-blue-50', 'dark:bg-blue-900/20');
            });
            dropZone.addEventListener('drop', (e) => {
                e.preventDefault();
                dropZone.classList.remove('border-primary', 'bg-blue-50', 'dark:bg-blue-900/20');
                const file = e.dataTransfer.files[0];
                if (file && file.name.endsWith('.csv')) {
                    handleCSVFile(file);
                }
            });
            document.getElementById('csvFile').addEventListener('change', (e) => {
                if (e.target.files[0]) {
                    handleCSVFile(e.target.files[0]);
                }
            });

            // Search and filter
            document.getElementById('searchInput').addEventListener('input', filterCertificates);
            document.getElementById('filterUsage').addEventListener('change', filterCertificates);
            document.getElementById('filterStatus').addEventListener('change', filterCertificates);
        }

        // Load and display statistics
        async function loadStatistics() {
            try {
                const response = await fetch('/api/client-certs/stats');
                const stats = await response.json();

                document.getElementById('totalCount').textContent = stats.total || 0;
                document.getElementById('activeCount').textContent = stats.active || 0;
                document.getElementById('revokedCount').textContent = stats.revoked || 0;

                const byUsage = stats.by_usage || {};
                const usageText = Object.entries(byUsage)
                    .map(([key, val]) => `${val} ${key}`)
                    .join(', ') || 'No certs';
                document.getElementById('usageBreakdown').textContent = usageText;
            } catch (e) {
                console.error('Error loading statistics:', e);
            }
        }

        // Load certificates
        async function loadCertificates() {
            try {
                const response = await fetch('/api/client-certs');
                const data = await response.json();
                certificatesData = data.certificates || [];
                renderCertificates();
            } catch (e) {
                console.error('Error loading certificates:', e);
            }
        }

        // Render certificate table
        function renderCertificates() {
            const tbody = document.getElementById('certTableBody');
            if (certificatesData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-8 text-center text-gray-500 dark:text-gray-400">No certificates found</td></tr>';
                return;
            }

            tbody.innerHTML = certificatesData.map(cert => {
                const expiresDate = new Date(cert.expires_at);
                const createdDate = new Date(cert.created_at);
                const isExpiringSoon = expiresDate - new Date() < 30 * 24 * 60 * 60 * 1000;

                return `
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">${cert.common_name}</td>
                        <td class="px-6 py-4 text-sm text-gray-600 dark:text-gray-300">${cert.email || '-'}</td>
                        <td class="px-6 py-4 text-sm"><span class="px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 rounded text-xs font-medium">${cert.cert_usage}</span></td>
                        <td class="px-6 py-4 text-sm text-gray-600 dark:text-gray-300">${createdDate.toLocaleDateString()}</td>
                        <td class="px-6 py-4 text-sm ${isExpiringSoon ? 'text-red-600 dark:text-red-400 font-semibold' : 'text-gray-600 dark:text-gray-300'}">${expiresDate.toLocaleDateString()}</td>
                        <td class="px-6 py-4 text-sm">
                            ${cert.revoked ? '<span class="px-2 py-1 bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300 rounded text-xs font-medium">Revoked</span>' : '<span class="px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 rounded text-xs font-medium">Active</span>'}
                        </td>
                        <td class="px-6 py-4 text-sm space-x-2">
                            <button onclick="showCertDetails('${cert.identifier}')" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"><i class="fas fa-eye"></i></button>
                            ${!cert.revoked ? `<button onclick="revokeCert('${cert.identifier}')" class="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"><i class="fas fa-ban"></i></button>` : ''}
                            <button onclick="renewCert('${cert.identifier}')" class="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300"><i class="fas fa-sync"></i></button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // Tab switching
        function switchTab(tab) {
            const singleForm = document.getElementById('createCertForm').parentElement;
            const batchForm = document.getElementById('batchForm');
            const singleBtn = document.getElementById('singleTabBtn');
            const batchBtn = document.getElementById('batchTabBtn');

            if (tab === 'single') {
                singleForm.classList.remove('hidden');
                batchForm.classList.add('hidden');
                singleBtn.classList.add('border-primary', 'text-primary');
                singleBtn.classList.remove('border-transparent', 'text-gray-600', 'dark:text-gray-300');
                batchBtn.classList.remove('border-primary', 'text-primary');
                batchBtn.classList.add('border-transparent', 'text-gray-600', 'dark:text-gray-300');
            } else {
                singleForm.classList.add('hidden');
                batchForm.classList.remove('hidden');
                batchBtn.classList.add('border-primary', 'text-primary');
                batchBtn.classList.remove('border-transparent', 'text-gray-600', 'dark:text-gray-300');
                singleBtn.classList.remove('border-primary', 'text-primary');
                singleBtn.classList.add('border-transparent', 'text-gray-600', 'dark:text-gray-300');
            }
        }

        // Handle single cert creation
        async function handleCreateCert(e) {
            e.preventDefault();

            const data = {
                common_name: document.getElementById('commonName').value,
                email: document.getElementById('email').value,
                organization: document.getElementById('organization').value,
                cert_usage: document.getElementById('certUsage').value,
                days_valid: parseInt(document.getElementById('daysValid').value),
                generate_key: document.getElementById('generateKey').checked,
                notes: document.getElementById('notes').value
            };

            try {
                const response = await fetch('/api/client-certs', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('Certificate created successfully!');
                    document.getElementById('createCertForm').reset();
                    loadCertificates();
                    loadStatistics();
                } else {
                    alert('Error creating certificate');
                }
            } catch (e) {
                console.error('Error:', e);
                alert('Error creating certificate');
            }
        }

        // Handle CSV file upload
        function handleCSVFile(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const csv = e.target.result;
                const rows = csv.split('\n').map(line => line.split(',').map(cell => cell.trim()));
                const headers = rows[0];
                const dataRows = rows.slice(1).filter(row => row[0]); // Skip empty rows

                // Show preview
                const headerRow = document.getElementById('headerRow');
                const previewBody = document.getElementById('previewBody');
                const rowCount = document.getElementById('rowCount');

                headerRow.innerHTML = headers.map(h => `<th class="px-3 py-2 text-left">${h}</th>`).join('');
                previewBody.innerHTML = dataRows.map(row =>
                    `<tr class="border-t">${row.map(cell => `<td class="px-3 py-2 text-gray-700 dark:text-gray-300">${cell}</td>`).join('')}</tr>`
                ).join('');

                rowCount.textContent = dataRows.length;
                document.getElementById('csvPreview').classList.remove('hidden');
                document.getElementById('submitBatchBtn').classList.remove('hidden');
                document.getElementById('certCountText').textContent = ` ${dataRows.length} Certificates`;

                // Store for submission
                window.csvData = { headers, rows: dataRows };
            };
            reader.readAsText(file);
        }

        // Filter certificates
        function filterCertificates() {
            const search = document.getElementById('searchInput').value.toLowerCase();
            const usage = document.getElementById('filterUsage').value;
            const status = document.getElementById('filterStatus').value;

            const filtered = certificatesData.filter(cert => {
                const matchSearch = !search || cert.common_name.toLowerCase().includes(search) || cert.email.toLowerCase().includes(search);
                const matchUsage = !usage || cert.cert_usage === usage;
                const matchStatus = !status || (status === 'active' && !cert.revoked) || (status === 'revoked' && cert.revoked);
                return matchSearch && matchUsage && matchStatus;
            });

            const tbody = document.getElementById('certTableBody');
            if (filtered.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-8 text-center text-gray-500">No certificates match filters</td></tr>';
            } else {
                certificatesData = [...certificatesData].filter(c => filtered.includes(c));
                renderCertificates();
            }
        }

        // Show certificate details
        function showCertDetails(id) {
            const cert = certificatesData.find(c => c.identifier === id);
            if (!cert) return;

            currentCertId = id;
            const modal = document.getElementById('certModal');
            const content = document.getElementById('modalContent');

            content.innerHTML = `
                <div><strong>Identifier:</strong> ${cert.identifier}</div>
                <div><strong>Common Name:</strong> ${cert.common_name}</div>
                <div><strong>Email:</strong> ${cert.email || 'N/A'}</div>
                <div><strong>Organization:</strong> ${cert.organization}</div>
                <div><strong>Usage:</strong> ${cert.cert_usage}</div>
                <div><strong>Serial:</strong> ${cert.serial_number}</div>
                <div><strong>Created:</strong> ${new Date(cert.created_at).toLocaleString()}</div>
                <div><strong>Expires:</strong> ${new Date(cert.expires_at).toLocaleString()}</div>
                <div><strong>Status:</strong> ${cert.revoked ? 'Revoked' : 'Active'}</div>
            `;

            modal.classList.remove('hidden');
        }

        function closeCertModal() {
            document.getElementById('certModal').classList.add('hidden');
        }

        function downloadCertFile(type) {
            if (!currentCertId) return;
            window.location.href = `/api/client-certs/${currentCertId}/download/${type}`;
        }

        // Revoke certificate
        async function revokeCert(id) {
            if (!confirm('Are you sure you want to revoke this certificate?')) return;

            try {
                const response = await fetch(`/api/client-certs/${id}/revoke`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ reason: 'User requested' })
                });

                if (response.ok) {
                    alert('Certificate revoked');
                    loadCertificates();
                    loadStatistics();
                } else {
                    alert('Error revoking certificate');
                }
            } catch (e) {
                console.error('Error:', e);
            }
        }

        // Renew certificate
        async function renewCert(id) {
            try {
                const response = await fetch(`/api/client-certs/${id}/renew`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                if (response.ok) {
                    alert('Certificate renewed successfully!');
                    loadCertificates();
                    loadStatistics();
                } else {
                    alert('Error renewing certificate');
                }
            } catch (e) {
                console.error('Error:', e);
            }
        }
    </script>
</body>
</html>
